
// 粘性导航栏类
class StickyNav extends Sticky {
    constructor({navEl, changeTab, data, initIndex = 0}) {
        super(navEl);

        this.wrapper = navEl;
        this.changeTab = changeTab;
        this.navData = data;
        this.initIndex = initIndex;

        this.navClassName = 'xu-nav-tab';
        this.navItemClassName = 'xu-nav-item';
        this.navItemActiveClassName = 'active';

        this.locked = false;

        this.initNavDom();
        this.initNavStyle();

        navEl.addEventListener('click', (e) => {
            if (this.locked) {
                return;
            }

            const targetEl = e.target;
            const {navItemActiveClassName, navItemClassName} = this;
            const {hasClass, addClass, removeClass} = this.domHandler;
            const navItemEls = document.getElementsByClassName(navItemClassName);
            if (!hasClass(targetEl, navItemClassName)) {
                return;
            }
            if (hasClass(targetEl, navItemActiveClassName)) {
                return;
            }

            for (let i = 0; i < navItemEls.length; i++) {
                removeClass(navItemEls[i], navItemActiveClassName);
            }
            addClass(targetEl, navItemActiveClassName);
            this.locked = true;

            changeTab(targetEl, () => {
                this.locked = false;
            });

        }, false);

    }
    initNavDom() {
        const {navData, wrapper, navClassName, navItemClassName, navItemActiveClassName, initIndex, domHandler} = this;

        domHandler.addClass(wrapper, navClassName);

        navData.forEach((content, index) => {
            const navItem = document.createElement('div');
            navItem.className = navItemClassName;
            if (initIndex === index) {
                navItem.className =  navItemClassName + ' ' + navItemActiveClassName;
            }
            domHandler.attr(navItem, 'data-index', index);
            domHandler.attr(navItem, 'data-tab', content);

            navItem.innerHTML = content;
            wrapper.appendChild(navItem);
        });
    }
    initNavStyle() {
        const headEl = document.head;
        const styleEl = document.createElement('style');

        styleEl.innerHTML = `
            .${this.navClassName} {
                box-sizing: border-box;
                display: flex;
                width: 100%;
                height: 92px;

                border-bottom: 1px solid rgba(0, 0, 0, 0.08);
                text-align: center;
                background: #fff;
            }
            .${this.navItemClassName} {
                display: flex;
                flex-flow: column;
                justify-content: center;
                flex: 1;
            }
        `;

        headEl.appendChild(styleEl);
    }
}

